import AuthApi from '@/api/AuthApi'
import AuthUtils from '@/utils/AuthUtils'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: AuthUtils.getToken(),
    userInfo: {},
    name: '',
    avatar: '',
    roles: [],
    permissions: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  }
}

const actions = {
  // 用户登录
  Login({ commit }, userInfo) {
    const params = {
      userName: userInfo.userName.trim(),
      password: userInfo.password,
      loginType: userInfo.loginType,
      code: userInfo.code,
      uuid: userInfo.uuid
    }
    return new Promise((resolve, reject) => {
      AuthApi.login(params).then(response => {
        AuthUtils.setToken(response.data)
        commit('SET_TOKEN', response.data)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取登录用户信息
  GetLoginUser({ commit, state }) {
    return new Promise((resolve, reject) => {
      AuthApi.getLoginUser().then(response => {
        const loginUser = response.data
        if (!loginUser) {
          reject('获取登录信息失败，请重新登录!')
        }
        if (!loginUser.roles || loginUser.roles <= 0) {
          reject('用户角色异常，请联系管理员！')
        }
        const user = loginUser.user
        commit('SET_ROLES', loginUser.roles)
        commit('SET_PERMISSIONS', loginUser.permissions)
        commit('SET_USERINFO', user)
        commit('SET_NAME', user.nickName)
        commit('SET_AVATAR', user.avatar ? user.avatar : require('@/assets/img/avatar.jpg'))
        resolve(response.data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  Logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      AuthApi.logout(state.token).then(() => {
        AuthUtils.removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  ResetToken({ commit }) {
    return new Promise(resolve => {
      AuthUtils.removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

